import os
from docxtpl import DocxTemplate
from xlsxtpl.writerx import BookWriter

class TemplateFiller:
    def __init__(self, template_path):
        self.template_path = template_path
        self.extension = os.path.splitext(template_path)[1].lower()
        self.template = self._load_template()

    def _load_template(self):
        if self.extension == '.xlsx':
            return BookWriter(self.template_path)
        elif self.extension == '.docx':
            return DocxTemplate(self.template_path)
        else:
            raise ValueError("Unsupported file format. Use .xlsx or .docx")

    def fill_template(self, data):
        if self.extension == '.xlsx':
            self._fill_xlsx(data)
        elif self.extension == '.docx':
            self._fill_docx(data)

    def _fill_xlsx(self, data):
        self.template.render_sheet(data)

    def _fill_docx(self, data):
        self.template.render(data)

    def save(self, output_path):
        if self.extension == '.xlsx':
            self.template.save(output_path)
        elif self.extension == '.docx':
            self.template.save(output_path)